package chapter_3;

import chapter_3.message.entity.AbstractMessage;
import chapter_3.message.entity.Candidate;
import chapter_3.message.entity.RequestMessage;
import chapter_3.message.entity.ResponseMessage;

import java.util.HashMap;
import java.util.Map;

/**
 * VoteService在服务器端，用于处理接收到的请求，并给客户端返回相应的响应。以及存储候选人信息
 */
public class VoteService {
    //候选人映射，键对应候选人id,值对应候选人票数
    private final Map<Integer, Integer> candidateMap = new HashMap<>();

    /**
     * 处理请求消息（查询或者投票），然后封装响应信息
     *
     * @param message 传递来的请求消息
     * @return
     */
    public ResponseMessage handleRequest(RequestMessage message) {
        ResponseMessage responseMessage = null;
        Candidate candidate = null;
        int candidateId = message.getCandidateId();
        int voteNumber;
        //判断是否为查询消息
        if (message.getInquiryFlag()) {
            System.out.println("接收到查询请求");
            //如果是查询消息，返回对应的候选人信息
            voteNumber = candidateMap.getOrDefault(candidateId, 0);
            candidate = new Candidate(candidateId, voteNumber);
        } else {
            System.out.println("接收到投票请求");
            int oldVoteNumber = candidateMap.getOrDefault(candidateId,0);
            candidateMap.put(candidateId, ++oldVoteNumber);
            candidate = new Candidate(candidateId,oldVoteNumber);
        }
        responseMessage = new ResponseMessage(message.getInquiryFlag(),candidate);
        return responseMessage;
    }

}
